// Precompile Composer custom diff2html Hogan templates to avoid runtime eval
// Usage: node scripts/compile-composer-templates.mjs

import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
let Hogan;
try {
	// Prefer root-level hogan.js if hoisted
	Hogan = await import('hogan.js');
} catch {
	// Fallback: resolve from diff2html's nested dependency to support pnpm non-hoisted layout
	const diff2htmlPkg = require.resolve('diff2html/package.json');
	const hoganPath = require.resolve('hogan.js', {
		paths: [require('node:path').join(require('node:path').dirname(diff2htmlPkg), 'node_modules')],
	});
	const { pathToFileURL } = await import('node:url');
	Hogan = await import(pathToFileURL(hoganPath).href);
}
Hogan = (Hogan && Hogan.default) || Hogan;

const repoRoot = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\//, '')), '..');
const srcPath = path.join(repoRoot, 'src/webviews/apps/plus/composer/components/diff/diff-templates.ts');
const outPath = path.join(repoRoot, 'src/webviews/apps/plus/composer/components/diff/diff-templates.compiled.ts');

const source = fs.readFileSync(srcPath, 'utf8');

// Extract template strings from the TS source
function extractTemplate(name) {
	const re = new RegExp(`export const ${name} = \`([\\s\\S]*?)\`;`);
	const m = source.match(re);
	if (!m) throw new Error(`Template ${name} not found in ${srcPath}`);
	return m[1];
}

const blockHeader = extractTemplate('blockHeaderTemplate');
const lineByLineFile = extractTemplate('lineByLineFileTemplate');
const sideBySideFile = extractTemplate('sideBySideFileTemplate');
const genericFilePath = extractTemplate('genericFilePathTemplate');

function precompile(name, tpl) {
	// Generate a code object compatible with new Hogan.Template(<code object>)
	const code = Hogan.compile(tpl, { asString: true });
	return `  "${name}": new Hogan.Template(${code})`;
}

const header = `/* eslint-disable */\n// @ts-nocheck\n// Generated by scripts/compile-composer-templates.mjs — DO NOT EDIT\nimport type { CompiledTemplates } from 'diff2html/lib-esm/hoganjs-utils';\nimport * as Hogan from 'hogan.js';\n`;

const body = `export const compiledComposerTemplates: CompiledTemplates = {\n${precompile(
	'generic-block-header',
	blockHeader,
)},\n${precompile('line-by-line-file-diff', lineByLineFile)},\n${precompile('side-by-side-file-diff', sideBySideFile)},\n${precompile('generic-file-path', genericFilePath)}\n};\n`;

fs.writeFileSync(outPath, header + body, 'utf8');
console.log(`Wrote ${outPath}`);
